/**
 * 统计用类
 */
package dms.model.util;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

/**
 * @author 李健
 *
 */
public class FindUtil {
	
	static final int COUNT_CONSTRAINT = 200;
	
	/**
	 * 方法对session生命周期不管理，只使用
	 * @param session
	 * @param params 位置参数
	 * @param query 统计总数HQL
	 * @return 统计数
	 */
	public static Long calculateAllCount(Session session, String countQuery, Collection params) {
		Long allCount = null;
		Query query = session.createQuery(countQuery);	

		if (params != null) {
			Iterator iter = params.iterator();
			int position = 0;
			while (iter.hasNext()) {
				query.setParameter(position, iter.next());
				position++;
			}
			
		}
		
		allCount = (Long) query.uniqueResult();
		return allCount;
	}
	/**
	 * 根据HQL查询语言，各个参数，开始位置，获取数获得 实体的list
	 * @param session
	 * @param findQuery
	 * @param params
	 * @param start
	 * @param count
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List getEntitiesByPage(Session session, String findQuery, Collection params, int start, int count) {
		List list = null;
		
		Query query = session.createQuery(findQuery);	
		
		if (params != null) {				
			Iterator iter = params.iterator();
			int position = 0;
			while (iter.hasNext()) {
				query.setParameter(position, iter.next());
				position++;
			}
		}
		
		if (start > 0) {
			query.setFirstResult(start);
		}
		if (count != 0) {
			if (count > COUNT_CONSTRAINT) {
				query.setMaxResults(COUNT_CONSTRAINT);
			}
		} 
		list = query.list();

		return list;
	}
}
